<?php
/**
 * Created by PhpStorm.
 * User: kevin
 * Date: 2015/7/9
 * Time: 11:26
 */

namespace Admin\Controller;
use Think\Controller;

class ProblemController extends AdminController{

	/**
	 *  新闻详情页
	 * 2016.6.29 teng
	 */
	public function index()
	{
		$order = 'is_top,datetime desc';
		$model = M('Problem');
		$list  = $this->lists($model,array(),$order);
		$this->assign('_list',$list);
		$this->meta_title = '问题列表';
		$this->display();

	}
	/**
	 *  新闻添加和修改
	 * 2016.6.29 teng
	 */
	public function problem_menu ()
	{
		if(IS_POST)
		{
			$data    = $_POST;
			$model	 = D('Problem');
			$data['is_top']     = intval($data['is_top'])==1?'1':2;
			$data['title']		= str_replace('"',"'",$data['title']);
			if($data['id'])      //修改
			{
				$data['id'] = intval($data['id']);
				$info 		= M('Problem')->find($data['id']);
				if($info)
				{
					$n_id   = $model->problem_edit($data);
					if($n_id>0)
					{
						$this->Problem_catch(1);  //更新缓存
						$this->success('修改成功',U('index'));
					}
					else
					{
						$this->error($this->showRegError($n_id));
					}
				}
				else
				{
					$this->error('数据不存在');
				}
			}
			else                //添加
			{
				$data['datetime']   = time();  //添加时间
				$n_id	= $model->problem_add($data);
				if($n_id>0)
				{
					$this->Problem_catch(1);  //更新缓存
					$this->success('添加成功',U('index'));
				}
				else
				{
					$this->error($this->showRegError($n_id));
				}
			}
		}
		else
		{
			if(I('id'))
			{
				$id 	= intval(I('id'));
				$info 	= M('Problem')->find($id);
				if($info)
				{
					$this->assign('info',$info);
				}
				else
				{
					JsLocation('数据不存在');
				}
			}
			$this->meta_title = '问题列表';
			$this->display();
		}
	}

//新闻删除
	public function problem_del(){
		if(I('id'))
		{
			$id 	= intval(I('id'));
			$info 	= M('Problem')->find($id);
			if($info)
			{
				if(M('Problem')->delete($info['id']))
				{
					$this->Problem_catch(1);  //更新缓存
					$this->success('删除成功',U('index'));
				}
				else
				{
					$this->error('删除失败');
				}
			}
			else
			{
				$this->error('数据不存在');
			}
		}
		else
		{
			$this->error('参数错误');
		}
	}

	private function showRegError($code = 0){
		switch ($code) {
			case -1:  $error = '标题长度必须在1-255个字符以内！'; break;
			case -2:  $error = '作者长度必须在1-100个字符以内！'; break;
			case -3:  $error = '来源长度必须在1-50个字符以内！'; break;
			case -4:  $error = '操作失败！'; break;
			case -5:  $error = '名称已被占用！'; break;
			case -6:  $error = '内容不能为空！'; break;
			default:  $error = '未知错误';
		}
		return $error;
	}

	private function Problem_catch($tag=''){
		if(empty($tag))		//读取缓存
		{
			return S('Problem_catch');
		}
		else				//写入缓存
		{
			S('Problem_catch',null);
			$order = 'is_top,datetime desc';
			$model = M('Problem');
//			$list  = $this->lists($model,array(),$order);
			$list  = $model->order($order)->getField('id,id,title,content,datetime,author,source,is_top');
			S('Problem_catch',$list);
			return true;
		}
	}

}
